import { Empty, Tag } from 'antd'
import './TimeLineScroll.less'
import React, { useRef, useEffect, useState } from 'react'
import { EditOutlined } from '@ant-design/icons'
import { useAppSelector } from '@/store/hooks'
// 组件属性接口定义
interface IProps {
  timelineData: {
    purchaseProduceScheduleTypeName: string
    delayDays: number
    planDate: string
    realDate: string
    fabricDeliverPercent: string
    purchaseProduceScheduleExtraVO: { expReason: string }
    [property: string]: any
  }[]
  onEditRemark: (event: any) => void
  onEditTime: (event: any) => void
  handleHasRead: (event: any) => void
}
const TimeLineScroll: React.FC<IProps> = ({ timelineData, onEditRemark, onEditTime, handleHasRead }) => {
  const timelineContainerRef = useRef<HTMLDivElement>(null) // 时间线容器的引用，用于获取容器宽度
  const timelineWrapperRef = useRef<HTMLDivElement>(null) // 时间线内容包裹层的引用，用于滚动
  const timelineScrollAreaRef = useRef<HTMLDivElement>(null) // 新增：可滚动区域的引用
  const [timelineLineWidth, setTimelineLineWidth] = useState(0) // 时间线长度状态
  const buttonCodeList = useAppSelector((state) => state.login.buttonCodeList) || []
  const updateKeyMap: Record<string, string[]> = {
    1: ['fabricPlanTime', 'fabricRealTime'],
    2: ['sampleClothingPlanTime', 'sampleClothingRealTime'],
    3: ['productInspectPlanTime', 'productInspectRealTime'],
    4: ['preMeetingPlanTime', 'preMeetingRealTime'],
    5: ['publishPlanTime', 'publishRealTime'],
    6: ['earlyInspectPlanTime', 'earlyInspectRealTime'],
    7: ['middleInspectPlanTime', 'middleInspectRealTime'],
    8: ['offlinePlanTime', 'offlineRealTime'],
    9: ['laterPlanTime', 'laterRealTime'],
  }

  // 检查是否需要显示滚动按钮
  const checkScrollStatus = () => {
    if (timelineScrollAreaRef.current && timelineWrapperRef.current) {
      // 计算时间线长度
      setTimelineLineWidth(timelineWrapperRef.current.scrollWidth)
    }
  }
  useEffect(() => {
    const timer = setTimeout(() => {
      checkScrollStatus()
    }, 100)
    return () => clearTimeout(timer)
  }, [timelineData, checkScrollStatus])
  // 监听容器宽度变化和滚动事件
  useEffect(() => {
    timelineScrollAreaRef.current?.addEventListener('scroll', checkScrollStatus) // 使用 timelineScrollAreaRef
    return () => {
      timelineScrollAreaRef.current?.removeEventListener('scroll', checkScrollStatus) // 使用 timelineScrollAreaRef
    }
  }, [timelineData, checkScrollStatus])

  // 找到从后往前第一个有 planDate 或 realDate 的节点的 index
  const getActiveIndex = (data: any[]) => {
    for (let i = data.length - 1; i >= 0; i--) {
      if (data[i]?.realDate) {
        return i
      }
    }
    return -1
  }
  const activeIndex = getActiveIndex(timelineData)

  // 渲染组件
  return (
    <React.Fragment>
      <div className="custom-timeline-container" ref={timelineContainerRef}>
        {timelineData?.length > 0 ? (
          <div className={`timeline-scroll-area show-scroll-buttons`} ref={timelineScrollAreaRef}>
            <div className="timeline-line" style={{ width: `${timelineLineWidth}px` }}></div>
            <div className="timeline-wrapper" ref={timelineWrapperRef}>
              {timelineData?.map((event: any, index: number) => {
                let dotClass = 'timeline-dot'
                if (index < activeIndex) {
                  dotClass += Number(event?.delayDays) > 0 ? ' has-delay' : ' finished'
                } else if (index === activeIndex) {
                  dotClass += Number(event?.delayDays) > 0 ? ' has-delay active' : ' active'
                }
                // 其余（index > activeIndex）保持默认（灰色）
                return (
                  <div key={index} className="timeline-item">
                    <div className={dotClass}></div>
                    <div className={`timeline-card-container ${index === activeIndex ? 'active' : ''}`}>
                      <div className="timeline-card">
                        <div className="timeline-card-header">
                          <div className="timeline-card-header-left">
                            <span
                              className={`title ${
                                Number(event?.delayDays) > 0 ? 'timeline-card-header-left-error' : ''
                              }`}
                            >
                              {Number(event?.delayDays) > 0 && event?.alreadyRead != 1 ? (
                                <span className="title-dot"></span>
                              ) : null}
                              {event?.purchaseProduceScheduleTypeName}
                            </span>
                            <span className="datetime-header">
                              {Number(event?.delayDays) > 0 ? '(' + '延期' + event?.delayDays + '天' + ')' : ''}
                            </span>
                          </div>
                          {[4, 6, 7, 9].includes(event?.purchaseProduceScheduleTypeCode) ? (
                            <span className="datetime-header-tag">
                              <Tag color={event?.haveQCOrder ? 'processing' : 'warning'}>
                                {event?.haveQCOrder ? '已通过' : '待执行'}
                              </Tag>
                            </span>
                          ) : null}
                          {event?.purchaseProduceScheduleTypeCode == 1 &&
                          event?.purchaseProduceScheduleExtraVO?.confirmTime == 1 ? (
                            <span className="datetime-header-tag">
                              <Tag color="processing">跟单已确认</Tag>
                            </span>
                          ) : null}
                        </div>
                        <div className="timeline-card-details">
                          <div className="timeline-time-info">
                            <div>
                              <span>计划时间：</span>
                              <span>{event?.planDate || '-'}</span>
                              {event?.purchaseProduceScheduleTypeCode == 1 &&
                              event?.purchaseProduceScheduleExtraVO?.confirmTime == 1 ? null : buttonCodeList?.includes(
                                  'EditProgress',
                                ) ? (
                                <EditOutlined
                                  onClick={() =>
                                    onEditTime({
                                      ...event,
                                      planDate: event?.planDate,
                                      type: 1,
                                      updateKey: updateKeyMap[event?.purchaseProduceScheduleTypeCode]?.[0],
                                    })
                                  }
                                  style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }}
                                />
                              ) : null}
                            </div>
                            <div>
                              <span>实际时间：</span>
                              <span>{event?.realDate || '-'}</span>
                              {event?.purchaseProduceScheduleTypeCode == 1 &&
                              event?.purchaseProduceScheduleExtraVO?.confirmTime == 1 ? null : buttonCodeList?.includes(
                                  'EditProgress',
                                ) ? (
                                <EditOutlined
                                  onClick={() =>
                                    onEditTime({
                                      ...event,
                                      realDate: event?.realDate,
                                      type: 2,
                                      updateKey: updateKeyMap[event?.purchaseProduceScheduleTypeCode]?.[1],
                                    })
                                  }
                                  style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }}
                                />
                              ) : null}
                            </div>
                          </div>
                          <div className="timeline-other-info">
                            {event?.purchaseProduceScheduleTypeCode == 1 ? (
                              <div>
                                <span>面料交货量：</span>
                                <span>{event?.fabricDeliverPercent || '-'}</span>
                              </div>
                            ) : null}
                            {[4, 6, 7, 9].includes(event?.purchaseProduceScheduleTypeCode) ? (
                              <div>
                                <span>QC人员：</span>
                                <span>{event?.qc || '-'}</span>
                              </div>
                            ) : null}
                            <div>
                              <span>节点备注：</span>
                              <span>{event?.purchaseProduceScheduleExtraVO?.expReason || '-'}</span>
                              {buttonCodeList?.includes('DeskMerProcessRemark') && (
                                <EditOutlined
                                  onClick={() => onEditRemark(event)}
                                  style={{ color: 'var(--primary-color)', cursor: 'pointer', marginLeft: 6 }}
                                />
                              )}
                            </div>
                          </div>
                          {Number(event?.delayDays) > 0 &&
                            event?.alreadyRead != 1 &&
                            buttonCodeList?.includes('DeskMerHasRead') && (
                              <div className="fly_btns" onClick={() => handleHasRead(event)}>
                                <button>标为已读</button>
                              </div>
                            )}
                        </div>
                      </div>
                    </div>
                  </div>
                )
              })}
            </div>
          </div>
        ) : (
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
        )}
      </div>
    </React.Fragment>
  )
}

export default TimeLineScroll
